/**
 * @program: leetcode002
 * @author: JCM
 * @create: 2022-11-24 18:13
 * @description:
 **/


class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        while(cur1 != null && cur2 != null) {
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        //让 cur 指向长的链表
        ListNode cur = cur1 != null ? l1 : l2;
        int tmp = 0;
        ListNode head = cur; //记录下头节点
        ListNode prev = cur; //记录下 cur 前面的节点
        while(cur!=null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int num = (n1+n2+tmp)%10;
            tmp = (n1 + n2 + tmp)/10;
            cur.val = num;
            prev = cur;
            cur = cur.next;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if(tmp == 1) {
            ListNode newNode = new ListNode(tmp,null);
            prev.next = newNode;
        }
        return head;
    }
}
public class leetCode002 {

}
